package com.whcoding.test.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.rholder.retry.Retryer;
import com.whcoding.test.constant.BaseConstant;
import com.whcoding.test.pojo.OrmCustomerVO;
import com.whcoding.test.service.CustomerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.concurrent.Callable;

/**
 * @program: spring-boot-learning
 * @description:
 * @author: whcoding
 * @create: 2022-04-20 17:47
 **/
@RestController
@RequestMapping(value = "/testRetry")
public class RetryController {

	private static final Logger logger = LoggerFactory.getLogger(RetryController.class);

	@Autowired
	private Retryer mailRetryer;

	@Autowired
	private Retryer msgRetryer;

	@Autowired
	CustomerService customerService;

	/**
	 * http://localhost:9180/demo/testRetry/testCustomerRetryer
	 * @return
	 */
	@GetMapping(value = "/testCustomerRetryer")
	public String testCustomerRetryer() {
		String resultMag = BaseConstant.DEFAULT_STRING_VALUE;
		OrmCustomerVO customerVO = customerService.getCustomerByID(200);
		if (Objects.isNull(customerVO)) {
			resultMag = requestRetryer();
		}
		return resultMag;
	}

	/**
	 * 请求重试
	 * @return
	 */
	private String requestRetryer() {
		String resp = "success";
		Callable<Boolean> mailCallable = new Callable<Boolean>() {
			int times = 0;
			@Override
			public Boolean call() {
				times++;
				logger.info("mail重试第{}次", times);
				//如果查询到数据怎退出
				return isPass(times);
//				if (times == 8) {
//					return true;
//				}
			}
		};

		try {
			mailRetryer.call(mailCallable);
		} catch (Exception e) {
			System.out.println(e);
			resp = "fail";
		}

		return resp;
	}


	@PostMapping(value = "testMsgRetryer")
	public String testMsgRetryer() {
		String resp = "success";

		Callable<Boolean> msgCallable = new Callable<Boolean>() {
			int times = 0;

			@Override
			public Boolean call() {
				times++;
				logger.info("msg重试第{}次", times);
				return times == 7;
			}
		};

		try {
			msgRetryer.call(msgCallable);
		} catch (Exception e) {
			System.out.println(e);
			resp = "fail";
		}

		return resp;
	}


	@PostMapping(value = "xzztryQueryResult.do")
	public JSONObject xzztryQueryResult(@RequestParam(value = "rnd") String rnd) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("total", 11);
		logger.info(jsonObject.toJSONString());
		return jsonObject;
	}

	private Boolean isPass(Integer num){
		return num == 3;
	}
}